package com.avengers.core.timer;

import com.avengers.core.kit.TimeKit;
import com.avengers.job.JobNoKit;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;

import java.math.RoundingMode;

/**
 * @author yu.wang
 * @since 2018-05-18 下午2:33
 */
public abstract class BaseTimer implements Job {
    private final String jobName;

    public BaseTimer(String jobName) {
        this.jobName = jobName;
    }

    @Override
    public final void execute(JobExecutionContext jobExecutionContext) {
        String jobNo = JobNoKit.create("job_");
        Logger logger = logger();
        if (isRunning()) {
            return;
        }
        long start = System.nanoTime();
        logger.info("*********** 【{}】 定时任务当前执行状态：{}，准备执行，任务编号：{} ***********", jobName, isRunning(), jobNo);
        setRunning(true);
        try {
            realExecute();
        } catch (Exception e) {
            logger.error("【{}】{} 定时任务执行异常", jobName, jobNo, e);
        } finally {
            setRunning(false);
            long useTimeMillis = TimeKit.useTimeMillisecond(start).setScale(0, RoundingMode.UP).longValue();
            logger.info("*********** 【{}】定时任务(编号：{})执行完成，共耗时 {}ms【{}】！修改执行状态：{} ***********",
                    jobName, jobNo, useTimeMillis
                    , TimeKit.useTimeStr(useTimeMillis)
                    , isRunning());
        }
    }

    /**
     * 逻辑处理
     */
    protected abstract void realExecute();

    /**
     * 是否运行
     */
    protected abstract boolean isRunning();

    /**
     * 标记运行
     */
    protected abstract void setRunning(boolean running);

    /**
     * 日志
     */
    protected abstract Logger logger();
}
